
import {PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns, ProDescriptionsItemProps} from '@ant-design/pro-components';
import {PageContainer, ProDescriptions, ProTable,} from '@ant-design/pro-components';
import '@umijs/max';
import {Button, Drawer, message} from 'antd';
import {SortOrder} from 'antd/es/table/interface';
import React, {useRef, useState} from 'react';
import {
  addUserUsingPost,
  deleteUserUsingPost,
  listUserByPageUsingGet,
  updateUserUsingPost
} from "@/services/api-backend/userController";
import UpdateModal from "@/pages/Admin/UserAdmin/components/UpdateModal";
import CreateModal from "@/pages/Admin/UserAdmin/components/CreateModal";


const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.User>();
  const [selectedRowsState, setSelectedRows] = useState<API.RuleListItem[]>([]);
  /**
   * @en-US Add node
   * @zh-CN 添加节点
   * @param fields
   */
  const handleAdd = async (fields: API.UserAddRequest) => {
    const hide = message.loading('正在添加');
    try {
      await addUserUsingPost({
        ...fields,
      });
      hide();
      message.success('创建成功');
      handleModalOpen(false)
      return true;
    } catch (error: any) {
      hide();
      message.error('创建失败' + error.message);
      return false;
    }
  };
  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param fields
   */
  const handleUpdate = async (fields: API.UserUpdateRequest) => {
    if (!currentRow) {
      return;
    }
    const hide = message.loading('修改中');
    try {
      console.log(fields)
      await updateUserUsingPost({
        ...fields,
        id: currentRow.id
      });
      hide();
      message.success('修改成功');
      handleUpdateModalOpen(false)
      return true;
    } catch (error) {
      hide();
      message.error('修改失败');
      return false;
    }
  };

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = async (record: API.DeleteRequest) => {
    const hide = message.loading('正在删除');
    if (!record) {
      message.error('删除失败.');
      return true;
    }
    try {
      await deleteUserUsingPost({
        id: record.id
      });
      hide();
      message.success('删除成功');
      actionRef.current?.reload()
      return true;
    } catch (error) {
      hide();
      message.error('删除失败.' + error.message);
      return false;
    }
  };


  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */

  const columns: ProColumns<API.UserVO>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      valueType: 'indexBorder', // 或 'index'，看你的 ProTable 是否需要边框
      width: '80px',
    },
    {
      title: '用户昵称',
      dataIndex: 'userName',
      valueType: 'text',
      formItemProps: {
        rules: [{ required: true, message: '请输入用户昵称' }],
        required: true,
      },
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      valueType: 'text',
      formItemProps: {
        rules: [
          { type: 'email', message: '请输入正确的邮箱格式' },
          { required: true, message: '请输入邮箱' },
        ],
        required: true,
      },
    },
    {
      title: '账号',
      dataIndex: 'userAccount',
      valueType: 'text',
      formItemProps: {
        rules: [{ required: true, message: '请输入账号' }],
        required: true,
      },
    },
    {
      title: '头像',
      dataIndex: 'userAvatar',
      valueType: 'avatar', // 如果你希望直接显示头像图片，可以用 'avatar'
      hideInSearch:true,
      hideInForm:true,
      // 或者用 'text'，然后自己 render 成 <Avatar> 或 <img>
      render: (_, record) => {
        const avatarUrl = record.userAvatar;
        if (!avatarUrl) return <span>暂无头像</span>;
        return (
          <img
            src={avatarUrl}
            alt="avatar"
            style={{ width: 40, height: 40, borderRadius: '50%' }}
          />
        );
      },
    },
    {
      title: '性别',
      dataIndex: 'gender',
      valueType: 'select',
      valueEnum: {
        0: { text: '未知', status: 'Default' },
        1: { text: '男', status: 'Success' },
        2: { text: '女', status: 'Processing' },
      },
      formItemProps: {
        rules: [{ required: true, message: '请选择性别' }],
      },
    },
    {
      title: '用户角色',
      dataIndex: 'userRole',
      valueType: 'select',
      valueEnum: {
        user: { text: '普通用户', status: 'Default' },
        admin: { text: '管理员', status: 'Processing' },
      },
      formItemProps: {
        rules: [{ required: true, message: '请选择用户角色' }],
      },
    },
    {
      title: '访问密钥',
      dataIndex: 'accessKey',
      valueType: 'text',
      hideInSearch:true,
      hideInForm:true,
      // 如果敏感信息，可以脱敏显示，比如只显示前几位
      render: (_, record) => {
        const key = record.accessKey || '';
        return key.length > 8 ? `${key.substring(0, 8)}****` : key;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch:true,
      hideInForm:true
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInSearch:true,
      hideInForm:true
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      sorter: true,
      render: (_, record) => [
        // React 使用 key 来识别列表中的每个元素，以便在更新列表时能够准确地判断新旧元素的对应关系，从而提高渲染性能
        <Button
          key="update"
          type="link"
          onClick={() => {
            handleUpdateModalOpen(true);
            setCurrentRow(record);
          }}
        >
          修改
        </Button>,
        record.status === 0 ? <Button
          key="online"
          type="link"
          onClick={() => {
            handleOnline(record);
          }}
        >
          发布
        </Button> : null,
        record.status === 1 ? <Button
          type={"text"}
          danger
          key="offline"
          onClick={() => {

            handleOffline(record);
          }}
        >
          下线
        </Button> : null,
        <Button
          type={"text"}
          danger
          key="remove"
          onClick={() => {

            handleRemove(record);
          }}
        >
          删除
        </Button>,

      ],
    },
  ];
  return (
    <PageContainer>
      {/*
         request 会在什么时候触发请求？
        一是当你刚打开页面或刚加载表格时；
        二是当你手动点击刷新按钮时；
        三是当你点击查询按钮时；
        */}
      <ProTable<API.RuleListItem, API.PageParams>
        headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        scroll={{x: 'max-content', y: 47 * 7}}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
            }}
          >
            <PlusOutlined/> 新建
          </Button>,
        ]}

        request={async (
          params,
          sort: Record<string, SortOrder>,
          filter: Record<string, React.ReactText[] | null>,
        ) => {
          const res: any = await listUserByPageUsingGet({
            ...params,
            sortField: "createTime",
            sortOrder: "descend"
          });
          // 如果后端请求给你返回了接口信息
          if (res?.data) {
            // 返回一个包含数据、成功状态和总数的对象
            return {
              data: res?.data.records || [],
              success: true,
              total: res?.data.total || 0,
            };
          }
          // 如果数据不存在，返回一个空数组，失败状态和零总数
          return {
            data: [],
            success: false,
            total: 0,
          };
        }}
        columns={columns}
        // rowSelection={{
        //   onChange: (_, selectedRows) => {
        //     setSelectedRows(selectedRows);
        //   },
        // }}
      />
      {/*{selectedRowsState?.length > 0 && (*/}
      {/*  <FooterToolbar*/}
      {/*    // extra={*/}
      {/*    //   <div>*/}
      {/*    //     已选择{' '}*/}
      {/*    //     <a*/}
      {/*    //       style={{*/}
      {/*    //         fontWeight: 600,*/}
      {/*    //       }}*/}
      {/*    //     >*/}
      {/*    //       {selectedRowsState.length}*/}
      {/*    //     </a>{' '}*/}
      {/*    //     项 &nbsp;&nbsp;*/}
      {/*    //     <span>*/}
      {/*    //       服务调用次数总计 {selectedRowsState.reduce((pre, item) => pre + item.callNo!, 0)} 万*/}
      {/*    //     </span>*/}
      {/*    //   </div>*/}
      {/*    // }*/}
      {/*  >*/}
      {/*    <Button*/}
      {/*      onClick={async () => {*/}
      {/*        await handleRemove(selectedRowsState);*/}
      {/*        setSelectedRows([]);*/}
      {/*        actionRef.current?.reloadAndRest?.();*/}
      {/*      }}*/}
      {/*    >*/}
      {/*      批量删除*/}
      {/*    </Button>*/}
      {/*    <Button type="primary">批量审批</Button>*/}
      {/*  </FooterToolbar>*/}
      {/*)}*/}

      <UpdateModal
        columns={columns}
        visible={updateModalOpen}
        onSubmit={async (value) => {
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalOpen(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current?.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalOpen(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        values={currentRow || {}}
      />
      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>

      <CreateModal
        columns={columns}
        onCancel={() => {
          handleModalOpen(false);
        }}
        onSubmit={(value) => {
          handleAdd(value);
        }}
        visible={createModalOpen}
      >
        {' '}
      </CreateModal>
    </PageContainer>
  );
};
export default TableList;
